<template>
  <div class="product-storage-confirm-page">
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <el-icon class="breadcrumb-icon">
            <Box />
          </el-icon>
          <div>
            <p class="breadcrumb-subtitle">仓库管理 · 产品入库</p>
            <h2 class="breadcrumb-heading">确认入库</h2>
          </div>
        </div>
        <div class="breadcrumb-status">
          <el-tag type="info" effect="dark" class="status-tag">
            当前状态：{{ statusLabel }}
          </el-tag>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" class="form-card">
      <div class="page-header">
        <div class="page-header__content">
          <div class="page-header__title">
            <div class="page-header__icon-wrapper">
              <el-icon class="page-header__icon"><DocumentChecked /></el-icon>
            </div>
            <div class="page-header__text">
              <h2>{{ formModel.inboundOrderName || "入库单详情" }}</h2>
              <p class="page-header__desc">
                请核对基础信息与入库明细，确认无误后提交
              </p>
            </div>
          </div>
          <el-tag type="warning" effect="light" class="page-header__tag">
            入库单编号：{{ formModel.inboundOrderNo || "-" }}
          </el-tag>
        </div>
      </div>

      <el-form :model="formModel" label-width="120px" class="confirm-form">
        <div class="form-section">
          <div class="section-header">
            <div class="section-header__main">
              <div class="section-header__icon">
                <el-icon><Document /></el-icon>
              </div>
              <div>
                <p class="section-title">基础信息</p>
                <p class="section-subtitle">单据信息及工单概览</p>
              </div>
            </div>
            <el-tag type="success" effect="light" size="small">只读信息</el-tag>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库单编号">
                <el-input v-model="formModel.inboundOrderNo" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库单名称">
                <el-input v-model="formModel.inboundOrderName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库日期">
                <el-input
                  :model-value="formatDate(formModel.inboundDate)"
                  readonly
                >
                  <template #prefix>
                    <el-icon><Calendar /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工单名称">
                <el-input v-model="formModel.workOrderName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工单编号">
                <el-input v-model="formModel.workOrderNo" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注">
                <el-input
                  v-model="formModel.remark"
                  type="textarea"
                  :rows="2"
                  readonly
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section detail-section">
          <div class="section-header">
            <div class="section-header__main">
              <div class="section-header__icon section-header__icon--detail">
                <el-icon><List /></el-icon>
              </div>
              <div>
                <p class="section-title">入库明细</p>
                <p class="section-subtitle">确认单条物料信息</p>
              </div>
            </div>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产品名称">
                <el-input v-model="detailModel.productName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品编号">
                <el-input v-model="detailModel.productNo" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="规格型号">
                <el-input v-model="detailModel.specification" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品类型">
                <el-input
                  :model-value="getProductTypeLabel(detailModel.productTypeId)"
                  readonly
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单位">
                <el-input v-model="detailModel.unit" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库数量">
                <el-input
                  :model-value="detailModel.inboundQuantity ?? '-'"
                  readonly
                >
                  <template #suffix>
                    {{ detailModel.unit || "pcs" }}
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="生产日期">
                <el-input
                  :model-value="formatDate(detailModel.productionDate)"
                  readonly
                >
                  <template #prefix>
                    <el-icon><Calendar /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到期日期">
                <el-input
                  :model-value="formatDate(detailModel.expiryDate)"
                  readonly
                >
                  <template #prefix>
                    <el-icon><Calendar /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="批次号">
                <el-input v-model="detailModel.batchNo" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库名称">
                <el-input v-model="detailModel.warehouseName" readonly>
                  <template #suffix>
                    <el-icon><OfficeBuilding /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="仓库负责人">
                <el-input v-model="detailModel.warehousePrincipal" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <div class="form-actions">
        <el-button @click="handleCancel" :disabled="submitting"
          >返回列表</el-button
        >
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleConfirm"
          class="confirm-btn"
          >确认入库</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {
  Box,
  Document,
  List,
  Calendar,
  DocumentChecked,
  OfficeBuilding,
} from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { computed, onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import https from "@/Http/http";
import moment from "moment";

interface ConfirmDetail {
  productName: string;
  productNo: string;
  specification?: string;
  productTypeId?: number | null;
  unit?: string;
  inboundQuantity?: number | null;
  batchNo?: string;
  productionDate?: string | null;
  expiryDate?: string | null;
  warehouseName?: string;
  warehousePrincipal?: string;
}

const router = useRouter();
const route = useRoute();

const submitting = ref(false);

const formModel = reactive({
  id: 0,
  inboundOrderNo: "",
  inboundOrderName: "",
  inboundDate: "",
  workOrderName: "",
  workOrderNo: "",
  remark: "",
  stats: 0,
});

const detailModel = reactive<ConfirmDetail>({
  productName: "",
  productNo: "",
  specification: "",
  productTypeId: null,
  unit: "",
  inboundQuantity: null,
  batchNo: "",
  productionDate: null,
  expiryDate: null,
  warehouseName: "",
  warehousePrincipal: "",
});

const STATUS_META: Record<number, string> = {
  0: "待入库",
  1: "确认入库",
  2: "已入库",
};

const statusLabel = computed(() => STATUS_META[formModel.stats] ?? "未知");

const formatDate = (value?: string | null) => {
  if (!value) return "-";
  return moment(value).format("YYYY-MM-DD");
};

const PRODUCT_TYPE_MAP: Record<number, string> = {
  1: "成品",
  2: "半成品",
  3: "其他",
};

const getProductTypeLabel = (value?: number | null) => {
  if (!value) return "-";
  return PRODUCT_TYPE_MAP[value] ?? "-";
};

const initializeFromRoute = () => {
  const { confirmData } = route.query;
  if (!confirmData) {
    ElMessage.warning("未获取到入库单数据，已返回列表");
    router.push("/ProductStorageList");
    return;
  }
  try {
    const parsed = JSON.parse(decodeURIComponent(confirmData as string));
    formModel.id = parsed.id ?? 0;
    formModel.inboundOrderNo = parsed.inboundOrderNo ?? "";
    formModel.inboundOrderName = parsed.inboundOrderName ?? "";
    formModel.inboundDate = parsed.inboundDate ?? "";
    formModel.workOrderName = parsed.workOrderName ?? "";
    formModel.workOrderNo = parsed.workOrderNo ?? "";
    formModel.remark = parsed.remark ?? "";
    formModel.stats = parsed.stats ?? 0;

    if (Array.isArray(parsed.detail) && parsed.detail.length) {
      Object.assign(detailModel, parsed.detail[0]);
    }
  } catch (error) {
    console.error("解析确认入库数据失败:", error);
    ElMessage.error("参数异常，已返回列表");
    router.push("/ProductStorageList");
  }
};

const handleConfirm = () => {
  if (formModel.stats !== 0) {
    ElMessage.warning("仅待入库状态可执行确认");
    return;
  }
  ElMessageBox.confirm("确认执行入库吗？确认后将进入“确认入库”状态", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      submitting.value = true;
      return https.Writes.put("/Warehouse/AffirmProduct", {
        Id: formModel.id,
        Stats: formModel.stats,
      });
    })
    .then((res: any) => {
      if ((res?.data?.code ?? res?.data?.Code) === 1) {
        ElMessage.success(res?.data?.msg ?? "确认入库成功");
        router.push("/ProductStorageList");
      } else {
        throw new Error(res?.data?.msg ?? "确认入库失败");
      }
    })
    .catch((error: any) => {
      if (error !== "cancel") {
        console.error("确认入库失败:", error);
        ElMessage.error(error?.message ?? "确认入库失败，请稍后重试");
      } else {
        ElMessage.info("已取消操作");
      }
    })
    .finally(() => {
      submitting.value = false;
    });
};

const handleCancel = () => {
  router.push("/ProductStorageList");
};

onMounted(() => {
  initializeFromRoute();
});
</script>

<style scoped>
.product-storage-confirm-page {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-bottom: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.breadcrumb-card {
  border-radius: 14px;
  border: none;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.breadcrumb-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.breadcrumb-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.breadcrumb-icon {
  font-size: 32px;
  color: #fff;
}

.breadcrumb-heading {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
}

.breadcrumb-status .status-tag {
  border-radius: 20px;
  padding: 10px 18px;
  font-weight: 600;
  background: rgba(0, 0, 0, 0.15);
  border: none;
}

.form-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background: #fff;
  padding-bottom: 16px;
}

.page-header {
  border-bottom: 1px solid #f0f2f5;
  padding-bottom: 18px;
  margin-bottom: 24px;
}

.page-header__content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.page-header__title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-header__icon-wrapper {
  width: 60px;
  height: 60px;
  border-radius: 18px;
  background: rgba(102, 126, 234, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-header__icon {
  font-size: 28px;
  color: #667eea;
}

.page-header__text h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header__desc {
  margin: 4px 0 0;
  color: #909399;
}

.page-header__tag {
  border-radius: 999px;
  padding: 10px 20px;
  font-weight: 600;
}

.confirm-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-section {
  border: 1px solid #f0f2f5;
  border-radius: 12px;
  padding: 20px 18px;
  background: linear-gradient(135deg, #fafbfc 0%, #f5f7fa 100%);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}

.section-header__main {
  display: flex;
  align-items: center;
  gap: 12px;
}

.section-header__icon {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  background: rgba(102, 126, 234, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #667eea;
}

.section-header__icon--detail {
  background: rgba(250, 173, 20, 0.15);
  color: #e6a23c;
}

.section-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.section-subtitle {
  margin: 2px 0 0;
  color: #909399;
  font-size: 13px;
}

.detail-section {
  background: #fffef7;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0 4px;
}

.confirm-btn {
  min-width: 140px;
}

:deep(.el-input__inner[readonly]) {
  color: #606266;
}
</style>































